<?
include("inc_security.php");

//Call class menu
$menu				= new menu();
$listAll			= $menu->getAllChild("categories_multi", "cat_id", "cat_parent_id", 0, "cat_type='product' AND cat_id IN (" . $gs_category . ") AND lang_id = " . $lang_id, "cat_id,cat_name,cat_type,cat_all_child", "cat_order ASC,cat_name ASC", "cat_has_child", 0);
unset($menu);

//Khai báo biến khi hiển thị danh sách
$gs_title		= $module_name . " | Danh sách";
$gs_action		= "listing.php" . getURL(0,0,0,1,"record_id");
$gs_redirect	= "listing.php" . getURL(0,0,0,1,"record_id");
$gs_errorMsg	= "";
$gs_alertMsg	= "";

/*****----- Quick Edit -----*****/
$action			= getValue("action", "str", "POST", "");
if($action == "execute"){
	
	//Get $record_id for edit data
	$arr_record_id	= getValue("record_id", "arr", "POST", "");
	if(is_array($arr_record_id)){
		
		//Loop array để update vào database
		for($i=0; $i<count($arr_record_id); $i++){
			
			$gs_errorMsg= "";
			
			//Lấy id của data cần sửa đổi
			$record_id	= intval($arr_record_id[$i]);
			
			$db_edit            = new db_query('SELECT * FROM ' . $gs_table . ' WHERE ' . $id_field . ' = ' . $record_id  . ' AND lang_id = ' . $lang_id);
			
			if (mysql_num_rows($db_edit->result) == 0)
			{
				//Redirect if can not find data
				redirect($gs_error);
			}
			$edit				= mysql_fetch_array($db_edit->result);
			unset($db_edit);
		
			//Lấy dữ liệu đề giữ nguyên trạng thái khi submit error
			$pro_category_id	= getValue('pro_category_id' . $record_id, 'int', 'POST', $edit['pro_category_id']);
			$pro_name			= getValue("pro_name" . $record_id, "str", "POST", $edit["pro_name"]);
			$pro_link			= getValue("pro_link" . $record_id, "str", "POST", $edit["pro_link"]);
			$pro_price		    = getValue('pro_price' . $record_id, 'dbl', 'POST', $edit['pro_price']);
			$pro_vat	       	= getValue('pro_vat' . $record_id, 'int', 'POST', $edit['pro_vat']);
			$pro_quantity       = getValue('pro_quantity' . $record_id, 'int', 'POST', $edit['pro_quantity']);
			$pro_quality 	    = getValue('pro_quality' . $record_id, 'int', 'POST', $edit['pro_quality']);
			$pro_warranty       = getValue('pro_warranty' . $record_id, 'int', 'POST', $edit['pro_warranty']);
			//$pro_status 	    = getValue('pro_status' . $record_id, 'int', 'POST', $edit['pro_status']);
			//$pro_last_updated	= time();
			
			$myform = new generate_form();
			//Add table insert data
			$myform->addTable($gs_table);
			if(strpos($gs_category, $pro_category_id . ",") === false){
				$gs_errorMsg .= "&bull; Bạn không được phép truy cập category này!<br />";
			}
			$myform->add("pro_category_id", "pro_category_id", 1, 1, 1, 1, "Bạn chưa chọn Danh mục sản phẩm.", 0, "");
			$myform->add("pro_name", "pro_name", 0, 1, " ", 1, "Bạn chưa nhập tên sản phẩm.", 0, "");
			$myform->add("pro_link", "pro_link", 0, 1, " ", 0, "", 0, "");
			$myform->add('pro_price','pro_price',3,1,0,0,'',0,'');
			$myform->add('pro_vat','pro_vat',1,1,0,0,'',0,'');
			$myform->add('pro_quantity','pro_quantity',1,1,0,0,'',0,'');
			$myform->add('pro_quality','pro_quality',1,1,0,0,'',0,'');
			$myform->add('pro_warranty','pro_warranty',1,1,0,0,'',0,'');
			//$myform->add('pro_status','pro_status',1,1,0,0,'',0,'');
			//$myform->add('pro_last_updated','pro_last_updated',1,1,0,0,'',0,'');
		
			//Check form data
			$gs_errorMsg .= $myform->checkdata();
			
			//Get $filename
			$filename = '';
			if ($gs_errorMsg == '')
			{
				$upload		= new upload($gs_fieldupload . $record_id, $gs_filepath, $gs_extension, $gs_filesize, $gs_insert_logo);
				$filename	= $upload->file_name;
				$gs_errorMsg .= $upload->warning_error;
			}
			
			if($gs_errorMsg == ""){
				
				if ($filename != '')
				{
					//Xóa ảnh cũ đi
					if($edit[$gs_fieldupload] != "") $upload->delete_file($gs_filepath, $edit[$gs_fieldupload]);
					//Upload new image
					$$gs_fieldupload = $filename;
					$myform->add($gs_fieldupload, $gs_fieldupload, 0, 1, "", 0, "", 0, "");
					$upload->resize_image($gs_filepath, $filename, $width_small_image, $height_small_image, "small_");
					$upload->resize_image($gs_filepath, $filename, $width_medium_image, $height_medium_image, "normal_");
					$upload->resize_image($gs_filepath, $filename, $width_larger_image, $height_larger_image, "larger_");
				}//End if ($filename != '')
				
				//Update to database
				$myform->removeHTML(0);
				$db_update = new db_execute($myform->generate_update_SQL($id_field, $record_id));
				unset($db_update);
				
			}//End if($gs_errorMsg == "")
			else{
				$gs_alertMsg .= "- Bạn không thay đổi được dữ liệu có ID = " . $record_id . ".\\n";
			}
			
			unset($myform);
			
		}//End for($i=0; $i<count($arr_record_id); $i++)
		
		//Nếu có data nào bị lỗi thì hiển thị thông báo alert message error rồi redirect
		if($gs_alertMsg != ""){
			echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">';
			echo '<script language="javascript">alert("Có những lỗi sau:\\n' . $gs_alertMsg . '"); window.location.href="' . $gs_redirect . '"</script>';
			exit();
		}
		//Ngược lại thì redirect luôn
		else redirect($gs_redirect);
		
	}//End if(is_array($arr_record_id))
	
}
/*****----- End Quick Edit -----*****/

$record_id	= getValue("record_id");

//Search data
$id			= getValue("id");
$keyword	= getValue("keyword", "str", "GET", "", 1);
$category	= getValue("category");
$hot		= getValue("hot");
$new		= getValue("new");
$promotion		= getValue("promotion");
$sqlWhere	= "";
//Tìm theo ID
if($id > 0)			$sqlWhere .= " AND pro_id = " . $id . " ";
//Tìm theo keyword
if($keyword != ""){
	if(validateDate($keyword) == 1){
		$startTime	= convertDateTime($keyword, "00:00:00");
		$endTime		= convertDateTime($keyword, "23:59:59");
		$sqlWhere	.= " AND pro_date >= " . $startTime . " AND pro_date <= " . $endTime . " ";
	}
	else{
		$sqlWhere	.= " AND (pro_name LIKE '%" . $keyword . "%' OR pro_teaser LIKE '%" . $keyword . "%' OR pro_description LIKE '%" . $keyword . "%') ";
	}
}

//Tìm theo category
if($category > 0){
	$db_cat	= new db_query("SELECT cat_all_child FROM categories_multi WHERE cat_id = " . $category);
	if($row	= mysql_fetch_array($db_cat->result)) $sqlWhere .= " AND cat_id IN (" . $row["cat_all_child"] . ") ";
	unset($db_cat);
}

if ($hot) $sqlWhere .= " AND pro_hot = 1 ";
if ($new) $sqlWhere .= " AND pro_new = 1 ";
if ($promotion) $sqlWhere .= " AND pro_promotion = 1 ";

//Sort data
$sort			= getValue("sort");
switch($sort){
	case 1: $sqlOrderBy = "pro_name ASC"; break;
	case 2: $sqlOrderBy = "pro_name DESC"; break;
	case 3: $sqlOrderBy = "pro_price ASC"; break;
	case 4: $sqlOrderBy = "pro_price DESC"; break;
	case 5: $sqlOrderBy = "pro_quantity ASC"; break;
	case 6: $sqlOrderBy = "pro_quantity DESC"; break;
	case 7: $sqlOrderBy = "pro_quality ASC"; break;
	case 8: $sqlOrderBy = "pro_quality DESC"; break;
	case 9: $sqlOrderBy = "pro_warranty ASC"; break;
	case 10: $sqlOrderBy = "pro_warranty DESC"; break;
	case 11: $sqlOrderBy = "ph_hits DESC"; break;
	case 12: $sqlOrderBy = "pro_date DESC"; break;
	default:$sqlOrderBy = "pro_date DESC"; break;
}

//Get page break params
$page_size		= 20;
$page_prefix	= "Trang: ";
$normal_class	= "page";
$selected_class= "page_current";
$previous		= "<";
$next			= ">";
$first			= "<<";
$last			= ">>";
$break_type		= 1;//"1 => << < 1 2 [3] 4 5 > >>", "2 => < 1 2 [3] 4 5 >", "3 => 1 2 [3] 4 5", "4 => < >"
$url			= getURL(0,0,1,1,"page");
$db_count		= new db_query("SELECT COUNT(*) AS count
										 FROM (categories_multi, " . $gs_table . ")
									 	 WHERE cat_id = pro_category_id AND cat_id IN (" . $gs_category . ") AND " . $id_field . " <> " . $record_id . " AND categories_multi.lang_id = " . $lang_id . $sqlWhere);
$listing_count	= mysql_fetch_array($db_count->result);
$total_record	= $listing_count["count"];
$current_page	= getValue("page", "int", "GET", 1);
if($total_record % $page_size == 0) $num_of_page = $total_record / $page_size;
else $num_of_page = (int)($total_record / $page_size) + 1;
if($current_page > $num_of_page) $current_page = $num_of_page;
if($current_page < 1) $current_page = 1;
$db_count->close();
unset($db_count);
//End get page break params
$db_listing	= new db_query("SELECT *
									 FROM (categories_multi, " . $gs_table . ") INNER JOIN product_hits ON pro_id = ph_id
									 WHERE cat_id = pro_category_id AND cat_id IN (" . $gs_category . ") AND " . $id_field . " <> " . $record_id . " AND categories_multi.lang_id = " . $lang_id . $sqlWhere . "
									 ORDER BY " . $sqlOrderBy . "
									 LIMIT " . ($current_page - 1) * $page_size . ", " . $page_size);
?>
<html>
<head>
<title><?=$gs_title?></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css" media="all">@import "../css/GSportal.css";</style>
<script language="javascript" src="../js/library.js"></script>
<script language="javascript" src="../js/tooltip.js"></script>
<script language="javascript" src="/js/AC_RunActiveContent.js"></script>
<script language="javascript" src="/js/jquery.min.js"></script>
<script language="javascript" src="/js/colorbox/colorbox.js"></script>
<link href="/js/colorbox/colorbox.css" rel="stylesheet" type="text/css" />

<script type="text/javascript">
	$(document).ready(function(){
		//assign the ColorBox event to elements
		$(".colorbox").colorbox({width:"100%", height:"100%", iframe:true});
	});
	
	// Close color box
	$(document).bind('cbox_closed', function(){
		OnCloseColorBox();
	});
</script>
</head>
<body>
<div class="bg_title_content">
<div class="content_title" style="float:left"><?=$gs_title?>: <font class="count"><?=format_number($total_record)?></font></div>
<div class="content_title" style="float:right"><a title="Thêm mới" href="add.php?category=<?=$category?>"><img align="absmiddle" border="0" hspace="5" src="<?=$gs_imagepath?>add.gif" />Thêm mới</a></div>
</div>
<div align="center" class="content">
<div align="left">
	<table class="text_normal" cellpadding="0" cellspacing="3">
    	<tr>
            <td nowrap="nowrap" style="padding-right:20px" class="text_normal">
                <b>Sắp xếp:</b>
                <?
                $url			= getURL(0,0,1,1,"sort");
				?>
                <a href="<?=$url?>&sort=11" class="text_link">Theo lượt xem</a> &nbsp;
                <a href="<?=$url?>&sort=12" class="text_link">Theo ngày cập nhật</a>
            </td>
            <td width="20"></td>
        </tr>
    </table>
</div>
<? //Page break and search data?>
<table width="98%" cellpadding="2" cellspacing="2">
	<tr>
		<td align="right">
			<table cellpadding="0" cellspacing="0">
			<form name="search" action="<?=getURL(0,0,1,0)?>" method="get">
				<tr>
					<td class="form_search" nowrap="nowrap">
                    	<input type="checkbox" value="1" name="hot"<? if ($hot) echo ' checked="checked"'?>>
                        Nổi bật &nbsp;
                        <input type="checkbox" value="1" name="new"<? if ($new) echo ' checked="checked"'?>>
                        Mới &nbsp;
                        <input type="checkbox" value="1" name="promotion"<? if ($promotion) echo ' checked="checked"'?>>
                        Khuyến mại &nbsp;
						ID:
						<input title="ID" type="text" class="form_control" id="id" name="id" value="<?=$id?>" maxlength="11" style="width:80px; text-align:right">&nbsp;
						Từ khóa:
						<input title="Từ khóa" type="text" class="form_control" id="keyword" name="keyword" value="<?=$keyword?>" maxlength="255" style="width:100px">&nbsp;
						<select title="Hiển thị theo danh mục" name="category" class="form_control">
							<option value="">--[Tất cả các mục]--</option>
						<?
						for($i=0; $i<count($listAll); $i++){
							$db_count	= new db_query("SELECT COUNT(*) AS count FROM " . $gs_table . " WHERE pro_category_id IN (" . $listAll[$i]["cat_all_child"] . ") AND lang_id = " . $lang_id);
							$row = mysql_fetch_array($db_count->result);
							unset($db_count);
						?>
							<option title="<?=$listAll[$i]["cat_name"]?> (<?=format_number($row["count"])?>)" value="<?=$listAll[$i]["cat_id"]?>" <? if($listAll[$i]["cat_id"] == $category){echo 'selected="selected"';}?>>
							<?
							for($j=0; $j<$listAll[$i]["level"]; $j++) echo " |--";
							echo " " . $listAll[$i]["cat_name"] . " (" . format_number($row["count"]). ")";
							?>
							</option>
						<?
						}// End for($i=0; $i<count($listAll); $i++)
						?>
						</select>
						<input type="hidden" name="sort" value="<?=$sort?>" />
					</td>
					<td class="form_search" style="padding-left:5px"><input title="Tìm kiếm" type="image" src="<?=$gs_imagepath?>search.gif" border="0"></td>
				</tr>
			</form>
			</table>
		</td>
	</tr>
</table>
<table width="98%" cellpadding="2" cellspacing="2">
	<tr>
		<td align="left"><?	if($total_record > $page_size){?><?=generatePageBar($page_prefix, $current_page, $page_size, $total_record, $url, $normal_class, $selected_class, $previous, $next, $first, $last, $break_type)?><? }?></td>
    	<td align="right">
        <? /*?>
			<div>
            	<a class="colorbox text_normal" href="excel_export.php" title="Xuất dữ liệu ra Excel"><img hspace="3" border="0" align="absmiddle" src="../images/excel_export.gif" />Xuất dữ liệu ra Excel</a>
				&nbsp;
				<a class="colorbox text_normal" href="excel_import.php" title="Cập nhật dữ liệu từ Excel"><img hspace="3" border="0" align="absmiddle" src="../images/excel_import.gif" />Cập nhật dữ liệu từ Excel</a>
			</div>
		<? */?>
		</td>
    </tr>
</table>
<? //End page break and search data?>
<table class="table" border="1" bordercolor="#e5e3e6" cellpadding="3" cellspacing="0" width="98%">
	<tr class="table_title_3">
		<td>Stt.</td>
		<td>Ảnh</td>
		<td>
			<div>Tên sản phẩm</div>
			<div>
				<?=generate_sort("asc", 1, $sort, $gs_imagepath)?>
				<?=generate_sort("desc", 2, $sort, $gs_imagepath)?>
			</div>
		</td>
		<td>
			<div>Giá bán</div>
			<div>
				<?=generate_sort("asc", 3, $sort, $gs_imagepath)?>
				<?=generate_sort("desc", 4, $sort, $gs_imagepath)?>
			</div>
		</td>
        <td>Khuyến<br>mại</td>
        <td>Mới</td>
        <td>Nổi bật</td>
		<td nowrap="nowrap">
			<div>Số lượng</div>
			<div>
				<?=generate_sort("asc", 5, $sort, $gs_imagepath)?>
				<?=generate_sort("desc", 6, $sort, $gs_imagepath)?>
			</div>
		</td>
        <td nowrap="nowrap">
			<div>Chất lượng</div>
			<div>
				<?=generate_sort("asc", 7, $sort, $gs_imagepath)?>
				<?=generate_sort("desc", 8, $sort, $gs_imagepath)?>
			</div>
		</td>
        <td>
			<div>Bảo hành</div>
			<div>
				<?=generate_sort("asc", 9, $sort, $gs_imagepath)?>
				<?=generate_sort("desc", 10, $sort, $gs_imagepath)?>
			</div>
		</td>
		<td>Lưu</td>
        <td>Xem</td>
        <td>Sửa</td>
        <td>Xóa</td>
	</tr>
<?
//Call class form
$form = new form();
$form->class_form_name = "form_name_2";
?>
<?
$record_id = getValue("record_id", "int", "POST");
//Đếm số thứ tự
$No = ($current_page - 1) * $page_size;
while($listing = mysql_fetch_array($db_listing->result)){
	$No++;
	$preview_link	= generate_detail_url($listing["cat_type"], $listing["cat_id"], $listing["pro_id"], $listing["pro_name"]);
?>
	<?
	$form->create_form("quick_edit_" . $No, $gs_action, "post", "multipart/form-data");
	?>
	<tr id="tr_<?=$No?>" <?=$gs_change_bg?>>
		<td class="No"><?=$No?></td>
		<td align="center">
			<div class="image_style">
			<? if($listing["pro_picture"] != ""){?>
				<a title="<?=htmlspecialbo($listing["pro_name"])?>" href="<?=$preview_link?>" target="_blank" onMouseOver="showtip('<img src=\'<?=$gs_filepath?>larger_<?=$listing["pro_picture"]?>\' />')" onMouseOut="hidetip()"><img src="<?=$gs_filepath?>small_<?=$listing["pro_picture"]?>" onError="this.src='<?=$gs_no_image?>'" /></a>
			<? }else{?>
				<a title="<?=htmlspecialbo($listing["pro_name"])?>" href="<?=$preview_link?>" target="_blank"><img class="style_image" width="40" src="<?=$gs_no_image?>" /></a>
			<? }?>
			</div>
			<? if($listing["pro_picture"] != ""){?><div style="margin-top:3px"><a href="javascript:if(confirm('Bạn có muốn xóa ảnh này không?')){window.location.href='delete.php?type=picture&record_id=<?=$listing["pro_id"]?>&redirect=<?=base64_encode(getURL())?>'}">[Xóa ảnh]</a></div><? }?>
		</td>
		<td align="center">
            <?=$form->create_table(2, 2, "");?>
            <?=$form->select_db_multi("Danh mục sản phẩm", "pro_category_id_" . $No, "pro_category_id" . $listing["pro_id"], $listAll, "cat_id", "cat_name", $listing["pro_category_id"], "Danh mục sản phẩm", 1, "", 1, 0, '', "")?>
			<?=$form->text("Tên", "pro_name_" . $No, "pro_name" . $listing["pro_id"], $listing["pro_name"], "Tên", 1, 203, "", 255, "", "", "")?>
			<?=$form->getFile("Ảnh", "pro_picture", "pro_picture" . $listing["pro_id"], "Ảnh sản phẩm", 0, 32, "", '<br />(Dung lượng tối đa <font color="#FF0000">' . $gs_filesize . ' Kb</font>)')?>
			<?=$form->text("Website", "pro_link_" . $No, "pro_link" . $listing["pro_id"], $listing["pro_link"], "Website", 0, 203, "", 255, "", "", "")?>
			<?=$form->close_table();?>
		</td>
		<td nowrap="nowrap" align="center">
        	<div>
            	<input type="text" style="color:#FF0000; text-align:right; width:70px" class="form_control" value="<?=$listing['pro_price']?>" name="pro_price<?=$listing["pro_id"]?>" id="pro_price_<?=$No?>" title="Giá">
			</div>
            <div style="padding-top:4px">
            	VAT:
				<select title="Thuế VAT" id="pro_vat_<?=$No?>" name="pro_vat" class="form_control">
                    <option value="0"<?=($listing['pro_vat'] == 0)?' selected="selected"':''?>>Đã có VAT</option>
                    <option value="1"<?=($listing['pro_vat'] == 1)?' selected="selected"':''?>>Không có VAT</option>
                </select>
            </div>
        </td>
        <td align="center"><a href="quickset.php?type=promotion&record_id=<?=$listing["pro_id"]?>&redirect=<?=base64_encode(getURL())?>"><img border="0" src="<?=$gs_imagepath?>check_small_<?=$listing["pro_promotion"]?>.gif" /></a></td>
        <td align="center"><a href="quickset.php?type=new&record_id=<?=$listing["pro_id"]?>&redirect=<?=base64_encode(getURL())?>"><img border="0" src="<?=$gs_imagepath?>check_small_<?=$listing["pro_new"]?>.gif" /></a></td>
        <td align="center"><a href="quickset.php?type=hot&record_id=<?=$listing["pro_id"]?>&redirect=<?=base64_encode(getURL())?>"><img border="0" src="<?=$gs_imagepath?>check_small_<?=$listing["pro_hot"]?>.gif" /></a></td>
        <td align="center">
        	<input type="text" style="text-align:right; width:35px" class="form_control" value="<?=$listing['pro_quantity']?>" name="pro_quantity<?=$listing["pro_id"]?>" id="pro_quantity_<?=$No?>" title="Số lượng">
        </td>
        <td nowrap="nowrap" align="center">
        	<select title="Chất lượng" id="pro_quality_1" name="pro_quality" class="form_control" style="width:45px">
                <option value="0"<?=($listing['pro_quality'] == 0)?' selected="selected"':''?>>Mới</option>
                <option value="1"<?=($listing['pro_quality'] == 1)?' selected="selected"':''?>>Cũ</option>
            </select>
        </td>
		<td align="center"><input type="text" style="text-align:right; width:35px" class="form_control" value="<?=$listing['pro_warranty']?>" name="pro_warranty<?=$listing["pro_id"]?>" id="pro_warranty_<?=$No?>" title="Bảo hành"><br>Tháng</td>
		<td align="center">
        	<input title="Lưu dữ liệu" type="image" hspace="5" src="<?=$gs_imagepath?>save.gif" onClick="MM_validateForm('pro_category_id_<?=$No?>','','R','pro_name_<?=$No?>','','R'); return document.MM_returnValue" />
		</td>
        <td align="center">
            <a title="Xem dữ liệu" href="<?=$preview_link?>" target="_blank"><img border="0" hspace="5" src="<?=$gs_imagepath?>preview.gif"></a>
		</td>
        <td align="center">
            <a title="Sửa dữ liệu" href="edit.php?record_id=<?=$listing["pro_id"]?>&redirect=<?=base64_encode(getURL())?>"><img border="0" hspace="5" src="<?=$gs_imagepath?>edit.gif"></a>
		</td>
        <td align="center">
            <img title="Xóa dữ liệu" hspace="5" src="<?=$gs_imagepath?>delete.gif" style="cursor:pointer" onClick="if(confirm('Bạn có muốn xóa dữ liệu này không?')){window.location.href='delete.php?record_id=<?=$listing["pro_id"]?>&redirect=<?=base64_encode(getURL())?>'}" />
		</td>
	</tr>
	<?=$form->hidden("record_id_" . $No, "record_id[]", $listing['pro_id'], "");?>
<?
}// End while($listing = mysql_fetch_array($db_listing->result))
?>
	<?=$form->hidden("action", "action", "execute", "");?>
<?
$form->close_form();
unset($form);
?>
</table>
<table width="98%" cellpadding="2" cellspacing="2">
	<tr>
		<? if($total_record > $page_size){?>
		<td><?=generatePageBar($page_prefix, $current_page, $page_size, $total_record, $url, $normal_class, $selected_class, $previous, $next, $first, $last, $break_type)?></td>
		<? }?>
		<td align="right"><a title="Go to top" accesskey="T" class="top" href="#">Lên trên<img align="absmiddle" border="0" hspace="5" src="<?=$gs_imagepath?>top.gif"></a></td>
	</tr>
</table>
</div>
</body>
</html>
<script language="javascript">ButtonLeftFrame();</script>